<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 插件管理组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Plugins_Edit extends Widget_Abstract_Options implements Widget_Interface_Do
{
    /**
     * @var bool
     */
    private $_configNoticed = false;

    /**
     * 手动配置插件变量
     *
     * @param       $pluginName 插件名称
     * @param array $settings 变量键值对
     * @param bool  $isPersonal 是否为私人变量
     */
    public function configPlugin($pluginName, array $settings, $isPersonal = false)
    {
        $pluginName = ($isPersonal ? '_' : '') . 'plugin:' . $pluginName;
        
        $option = $this->select()->where('name = ?', $pluginName)->fetchRow();

        if (empty($settings)) {
            if (!empty($option)) {
                $this->delete($pluginName);
            }
        } else {
            if (empty($option)) {
                $this->insert(array('name'  =>  $pluginName,'value' =>  serialize($settings)));
            } else {
                $value = unserialize($option['value']);
                $value = array_merge($value, $settings);
                $this->update($pluginName, serialize($value));
            }
        }
    }

    /**
     * 启用插件
     *
     * @param $pluginName
     * @throws Widget_Exception
     */
    public function activate($pluginName)
    {
        /** 获取插件入口 */
		$pluginInfo = $this->options->pluginInfo($pluginName);
        if(empty($pluginInfo)){
			$this->result->set(-1, 'Missing Plugin ' . $pluginName);
		}
        list($pluginFileName, $className) = $pluginInfo;
        $info = Plugins::parseInfo($pluginFileName);

        /** 检测依赖信息 */
        list ($version, $build) = explode('/', Common::VERSION);
        if (Plugins::checkDependence($build, $info['dependence'])) {

            /** 获取已启用插件 */
            $plugins = Plugins::export();

            /** 判断启用是否成功 */
            if (isset($plugins[$pluginName])) {
				$this->result->set(-1, _t('插件已启用'));
            }

            /** 载入插件 */
            require_once $pluginFileName;

            /** 检查类是否已定义 || 检查类的方法是否存在 */
            if (!class_exists($className) || !method_exists($className, 'activate')) {
				$this->result->set(-1, _t('无法启用插件'));
            }

            try {
                $result = call_user_func(array($className, 'activate'));
                Plugins::activate($pluginName);
                $this->update('plugins', serialize(Plugins::export()));
				$this->options->__set('plugins', Plugins::export());
				
				
            } catch (Plugins_Exception $e) {
                /** 截获异常 */
				$this->result->set(-1, $e->getMessage());
            }

            $form = new Form();
            call_user_func(array($className, 'config'), $form);

            $options = $form->getValues();

            if ($options && !$this->configHandle($pluginName, $options, true)) {
                $this->configPlugin($pluginName, $options);
            }
        } else {
            $result = _t('<a href="%s">%s</a> 无法在此版本的cola下正常工作', $info['homepage'], $info['title']);
        }

        if (isset($result) && is_string($result)) {
            $this->result->set(-1, $result, array('pluginName'=>$pluginName));
        } else {
			Plugins::refresh();
            $this->result->set(0, _t('插件已经被启用'), array('pluginName'=>$pluginName));
        }
    }

    /**
     * 禁用插件
     *
     * @param $pluginName
     * @throws Widget_Exception
     * @throws Exception
     * @throws Plugins_Exception
     */
    public function deactivate($pluginName)
    {
        /** 获取已启用插件 */
        $plugins = Plugins::export();

        $pluginInfo = $this->options->pluginInfo($pluginName);

        /** 判断是否是已启用的插件 */
        if (empty($pluginInfo) || !isset($plugins[$pluginName])) {
			$this->result->set(-1, _t('无法禁用插件'));
        }

		list($pluginFileName, $className) = $pluginInfo;

        /** 载入插件 */
        //require_once $pluginFileName;

        /** 判断 */
        //if (!class_exists($className) || !method_exists($className, 'deactivate')) {
        //    throw new Widget_Exception(_t('无法禁用插件'), 500);
        //}

        try {
            $result = call_user_func(array($className, 'deactivate'));
        } catch (Plugins_Exception $e) {
            /** 截获异常 */
            $this->result->set(-1, $e->getMessage());
        }

        Plugins::deactivate($pluginName);

        $this->update('plugins', serialize(Plugins::export()));
		$this->options->__set('plugins', Plugins::export());

        $this->delete('plugin:' . $pluginName);
        $this->delete('_plugin:' . $pluginName);

        if (isset($result) && is_string($result)) {
            $this->result->set(-1, $result, array('pluginName'=>$pluginName));
        } else {
			Plugins::refresh();
            $this->result->set(0, _t('插件已经被禁用'), array('pluginName'=>$pluginName));
        }
    }

    /**
     * 配置插件
     *
     * @param $pluginName
     * @access public
     * @return void
     */
    public function config($pluginName)
    {
        $form = $this->widget('Widget_Plugins_Config')->form();

		/** 验证格式 */
        if ($message = $form->validate()) {
            $this->result->set(key($message), current($message));
        }

        $settings = $form->getAllRequest();

        if (!$this->configHandle($pluginName, $settings, false)) {
            self::configPlugin($pluginName, $settings);
        }

        if (!$this->_configNoticed) {
            /** 提示信息 */
            $this->result->set(0, _t("插件设置已经保存"), array('location'=>$this->options->ucenterUrl('plugins', false)));
        }

        /** 转向原页 */
		$this->result->set(-1, NULL, array('location'=>$this->options->ucenterUrl('plugins', false)));
    }

    /**
     * 用自有函数处理配置信息
     *
     * @access public
     * @param string $pluginName 插件名称
     * @param array $settings 配置值
     * @param boolean $isInit 是否为初始化
     * @return boolean
     */
    public function configHandle($pluginName, array $settings, $isInit)
    {
        /** 获取插件入口 */
		$pluginInfo = $this->options->pluginInfo($pluginName);
        if(empty($pluginInfo)){
			$this->result->set(-1, 'Missing Plugin ' . $pluginName);
		}
		
        list($pluginFileName, $className) = $pluginInfo;

        if (!$isInit && method_exists($className, 'configCheck')) {
            $result = call_user_func(array($className, 'configCheck'), $settings);

            if (!empty($result) && is_string($result)) {
                $this->result->set(-1, $result);
                $this->_configNoticed = true;
            }
        }

        if (method_exists($className, 'configHandle')) {
            call_user_func(array($className, 'configHandle'), $settings, $isInit);
            return true;
        }

        return false;
    }

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->user->pass('admin');
        $this->security->protect();
        $this->on($this->request->is('activate'))->activate($this->request->filter('strip_tags')->activate);
        $this->on($this->request->is('deactivate'))->deactivate($this->request->filter('strip_tags')->deactivate);
        $this->on($this->request->is('config'))->config($this->request->filter('strip_tags')->config);
        $this->result->set(404, _t('请求的资源不存在'));
    }
}
